package com.biz.primus.ms.order.service.helper;

import com.biz.primus.base.exception.BizSilentException;
import com.biz.primus.base.exception.utils.AssertUtils;
import com.biz.primus.model.oms.stream.ReturnStateChannel;
import com.biz.primus.model.oms.vo.UserOrderOperationRequest;
import com.biz.primus.model.oms.vo.returns.UserOperateReturnRequestVo;
import com.biz.primus.model.order.enums.ReturnState;
import com.biz.primus.model.order.exception.OrderException;
import com.biz.primus.ms.order.convertor.ReturnOrderConvertor;
import com.biz.primus.ms.order.dao.po.ReturnOrder;
import com.biz.primus.ms.order.dao.repository.ReturnOrderRepository;
import com.biz.primus.ms.order.feign.OmsFeignClient;
import com.biz.primus.ms.order.stream.ReturnStateSink;
import com.biz.primus.ms.order.stream.ReturnStateSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;

/**
 * 退货单状态助理
 *
 * @author Tiger Feng
 * @date 2017年11月23日
 */
@Service
public class ReturnStateStreamHelper {
    @Autowired
    private ReturnStateSource returnStateSource;
    //=========================================
    @Autowired
    private ReturnOrderRepository returnOrderRepository;
    @Autowired
    private OmsFeignClient omsService;

    /**
     * 接收审核通过的退货单
     *
     * @param stateStreamDataMessage 退货单信息
     */
    @StreamListener(ReturnStateSink.RETURN_AUDITED_AND_PASS)
    public void receiveAuditAgreeState(Message<ReturnStateChannel.ReturnStateStreamData> stateStreamDataMessage) {
        // 退货单编码
        ReturnOrder returnOrder = returnOrderRepository.findByReturnCode(stateStreamDataMessage.getPayload().getReturnCode());
        AssertUtils.notNull(returnOrder, OrderException.RETURN_ORDER_IS_NULL);
        switch (returnOrder.getReturnState()) {
            case AUDITING:
                // 状态为审核中
                break;
            case RETURNING:
                // "审核通过"直接进入"退货中"，重复操作直接终止
                return;
            default:
                throw new BizSilentException(OrderException.RETURN_STATE_ERROR);
        }
        returnOrder.setReturnState(ReturnState.RETURNING);
        returnOrder.setUpdateTimestamp(new Timestamp(System.currentTimeMillis()));
        returnOrderRepository.save(returnOrder);
    }

    /**
     * 接收审核未通过的退货单
     *
     * @param stateStreamDataMessage 退货单信息
     */
    @StreamListener(ReturnStateSink.RETURN_AUDITED_AND_REJECT)
    public void receiveAuditDisagreeState(Message<ReturnStateChannel.ReturnStateStreamData> stateStreamDataMessage) {
        // 退货单编码
        ReturnOrder returnOrder = returnOrderRepository.findByReturnCode(stateStreamDataMessage.getPayload().getReturnCode());
        AssertUtils.notNull(returnOrder, OrderException.RETURN_ORDER_IS_NULL);
        switch (returnOrder.getReturnState()) {
            case AUDITING:
                // 状态为审核中
                break;
            case DISAGREE:
                // 审核未通过的，重复操作直接终止
                return;
            default:
                throw new BizSilentException(OrderException.RETURN_STATE_ERROR);
        }
        returnOrder.setReturnState(ReturnState.DISAGREE);
        returnOrder.setUpdateTimestamp(new Timestamp(System.currentTimeMillis()));
        returnOrderRepository.save(returnOrder);
    }

    /**
     * 接收验收入库的退货单，及门店收到客户退还的商品
     *
     * @param stateStreamDataMessage 退货单信息
     */
    @StreamListener(ReturnStateSink.RETURN_FINISHED)
    public void receiveReturnFinish(Message<ReturnStateChannel.ReturnStateStreamData> stateStreamDataMessage) {
        // 退货单编码
        ReturnOrder returnOrder = returnOrderRepository.findByReturnCode(stateStreamDataMessage.getPayload().getReturnCode());
        AssertUtils.notNull(returnOrder, OrderException.RETURN_ORDER_IS_NULL);
        switch (returnOrder.getReturnState()) {
            case RETURNING:
                // 状态为退货中
                break;
            case WAIT_REFUND:
                // 已验收入库，重复操作直接终止
                return;
            default:
                throw new BizSilentException(OrderException.RETURN_STATE_ERROR);
        }
        returnOrder.setReturnState(ReturnState.WAIT_REFUND);
        returnOrder.setUpdateTimestamp(new Timestamp(System.currentTimeMillis()));
        returnOrderRepository.save(returnOrder);
    }

    /**
     * 接收退款完成的退货单
     *
     * @param stateStreamDataMessage 退货单信息
     */
    @StreamListener(ReturnStateSink.RETURN_REFUND_FINISHED)
    public void receiveRefundFinish(Message<ReturnStateChannel.ReturnStateStreamData> stateStreamDataMessage) {
        // 退货单编码
        ReturnOrder returnOrder = returnOrderRepository.findByReturnCode(stateStreamDataMessage.getPayload().getReturnCode());
        AssertUtils.notNull(returnOrder, OrderException.RETURN_ORDER_IS_NULL);
        switch (returnOrder.getReturnState()) {
            case WAIT_REFUND:
                break;
            case REFUNDED:
                // 已退款，重复操作直接终止
                return;
            default:
                throw new BizSilentException(OrderException.RETURN_STATE_ERROR);
        }
        returnOrder.setReturnState(ReturnState.REFUNDED);
        returnOrder.setUpdateTimestamp(new Timestamp(System.currentTimeMillis()));
        returnOrderRepository.save(returnOrder);
    }

    /**
     * 通知OMS，取消退货单（审核前可以取消）-- 接口
     *
     * @param returnOrder 退货单
     */
    public void sendCancelReturnOrder(ReturnOrder returnOrder) {
        UserOperateReturnRequestVo requestVo = ReturnOrderConvertor.getOmsReturnOrderCancelVOFromPO(returnOrder);
        omsService.cancelReturns(requestVo);
    }

}
